package com.common.allCommon;

import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.os.Build;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.common.StarAppConfig;
import com.common.StarAppConst;
import com.product.android.business.ApplicationVariable;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtils {
	 public static void  restoreCurrentUser(){
		if (null == ApplicationVariable.INSTANCE.getCurrentUserInfo()) {
			com.product.android.business.bean.UserInfo info=StarappApplicationVariable.INSTANCE.getLastLoginUser();
			StarappApplicationVariable.INSTANCE.setCurrentUserInfo(info);
		}
	 }
	 
	 /**
	 * 
	 * @n<b>函数名称</b>     :getGroupTrantKey
	 * @brief                返回群操作的key(比如转让群、添加群成员等)
	 * @see 
	 * @since    Ver 1.1
	 * @param  @param gid       群ID
	 * @param  @param groupType 群类型
	 * @param  @param operation 操作类型（见com.common.Const.GROUP_OP类）
	 * @param  @return
	 * @return String
	 * @<b>作者</b>          :  zhy
	 * @<b>创建时间</b>      :  2014-1-23下午6:51:50
	 */
	public static String getGroupOperationKey(String gid,String operation){
		StringBuffer key=new StringBuffer();
		key.append(gid);
		key.append(operation);
		return key.toString();
	}
	
	
	/**
	 * @n<b>函数名称</b>     :isBackgroundRunning
	 * @brief 是否运行在后台
	 * @version    Ver 1.3.3_modularization
	 * @param  @param context
	 * @param  @return
	 * @return boolean
	 * @<b>作者</b>          :  cb
	 * @<b>创建时间</b>      :  2014-2-26下午8:54:30      
	*/
	@TargetApi(Build.VERSION_CODES.CUPCAKE)
	public static boolean  isBackgroundRunning() {
		Context context=ApplicationVariable.INSTANCE.applicationContext; 
		ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);

		if (activityManager == null)
			return false;
		// get running application processes
		List<ActivityManager.RunningAppProcessInfo> processList = activityManager
				.getRunningAppProcesses();
		for (ActivityManager.RunningAppProcessInfo process : processList) {
			if (process.processName.startsWith(context.getPackageName())) {
				boolean isBackground = process.importance != RunningAppProcessInfo.IMPORTANCE_FOREGROUND
						&& process.importance != RunningAppProcessInfo.IMPORTANCE_VISIBLE;
				if (isBackground)
					return true;
				else
					return false;
			}
		}
		return false;

	}
	
	/**
	 * @n<b>函数名称</b>     :getContentLength
	 * @brief 获取文件的长度
	 * @see
	 * @since    Ver 1.2
	 * @param  @param urlConnection
	 * @param  @return
	 * @return long
	 * @<b>作者</b>          :  cb
	 * @<b>创建时间</b>      :  2013-8-20下午3:10:58      
	*/
	public static long getContentLength(HttpURLConnection urlConnection){
		String range=urlConnection.getHeaderField("Content-Range");
		if (TextUtils.isEmpty(range)){
			return 0;
		}
		String[] section = range.split("/");
		try {
			// Parse for the instance length
			return Long.parseLong(section[1]);
		} catch (NumberFormatException e) {
			Log.d("debug",String.format("The HttpResponse contains an invalid instance-length: %s",range));
		}
		return 0;
	}
	
	
	/**
	 * @n<b>函数名称</b>     :isHtml
	 * @brief 判断某个字符串是不是个URL
	 * @version    Ver 1.3.3_modularization
	 * @param  @param str
	 * @param  @return
	 * @return boolean
	 * @<b>作者</b>          :  cb
	 * @<b>创建时间</b>      :  2014-3-13下午3:42:12      
	*/
	public static boolean isHtml(String str){
		if (TextUtils.isEmpty(str)){
			return false;
		}
		Matcher matcher = RegexUtils.WEB_URL.matcher(str);
		return matcher.find();
	}
	
	
	/**
	 * @n<b>函数名称</b>     :isNumeric
	 * @brief 判断某个字符串是否全是数字
	 * @version    Ver 1.3.3_modularization
	 * @param  @param str
	 * @param  @return
	 * @return boolean
	 * @<b>作者</b>          :  cb
	 * @<b>创建时间</b>      :  2014-3-13下午3:43:14      
	*/
	public static boolean isNumeric(String str){   
		if(TextUtils.isEmpty(str)) return false;
	    Pattern pattern = Pattern.compile("[0-9]*");   
	    return pattern.matcher(str).matches();      
	} 
	
	/**
	 * @n<b>函数名称</b>     :isBitmapFileAvaiable
	 * @brief 根据路径判断图片文件是否可用
	 * @version    Ver 1.3.3_modularization
	 * @param  @param path
	 * @param  @return
	 * @return boolean
	 * @<b>作者</b>          :  cb
	 * @<b>创建时间</b>      :  2014-3-18下午5:41:24      
	*/
	public static boolean isBitmapFileAvaiable(String path){
		if (TextUtils.isEmpty(path)){
			return false;
		}
		try {
			Options options=new Options();
			options.inJustDecodeBounds=true;
			BitmapFactory.decodeFile(path, options);
			if (options.outHeight>0 && options.outWidth>0){
				Bitmap bmp=BitmapFactory.decodeFile(path);
				if (bmp!=null){
					return true;
				}
			}
		} catch (Exception e) {
			
		}
		return false;
	}
	
	/**
	 * @n<b>函数名称</b>     :recycleBitmap
	 * @brief 回收图片
	 * @version    Ver 1.3.3_modularization
	 * @param  @param bitmap
	 * @return void
	 * @<b>作者</b>          :  cb
	 * @<b>创建时间</b>      :  2014-3-24下午2:05:32      
	*/
	public static void recycleBitmap(Bitmap bitmap){
		if (bitmap!=null){
			android.util.Log.d("bitmap", "recycle bitmap:"+bitmap);
			bitmap.recycle();
			bitmap=null;
		}
	}
	
	/**
	 * @n<b>函数名称</b>     :isGifFile
	 * @brief 判断某个图片是否GIF格式
	 * @version    Ver 1.3.3_modularization
	 * @param  @param path
	 * @param  @return
	 * @return boolean
	 * @<b>作者</b>          :  cb
	 * @<b>创建时间</b>      :  2014-3-24下午2:10:14      
	*/
	public static boolean isGifFile(String path){
		if (TextUtils.isEmpty(path)){
			return false;
		}
		boolean isGif=false;
		InputStream stream=null;
		try {
			stream=new FileInputStream(path);
			byte[] head=new byte[3];
			stream.read(head);
			String imgType=new String(head);
			isGif=imgType.equalsIgnoreCase("gif");
		} catch (Exception e) {
		} finally {
			if (stream!=null){
				try {
					stream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}				
			}
		}
		return isGif;
	}
	
	/**
	 * dip转像素
	 * 
	 * @n<b>函数名称</b> :dipToPx
	 * @brief
	 * @see
	 * @version Ver 0.3
	 * @param @param context
	 * @param @param dipValue
	 * @param @return
	 * @return int
	 * @<b>作者</b> : HuangYK
	 * @<b>创建时间</b> : 2014-3-19下午5:47:23
	 */
	public static int dipToPx(Context context, int dipValue) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
				dipValue, context.getResources().getDisplayMetrics());
	}
	
	/**
	 * 弹出软键盘
	 * 
	 * @param context
	 * @param view
	 */
	public static void showSoftInputMethod(final Context context,
			final View view) {
		new Handler().postDelayed(new Runnable() {

			@TargetApi(Build.VERSION_CODES.CUPCAKE)
			@Override
			public void run() {
				((InputMethodManager) context
						.getSystemService(Context.INPUT_METHOD_SERVICE))
						.showSoftInput(view, 0);
			}
		}, 100);

	}

    /**
     * 判断是否为周杰倫版本,是,返回true;   否,返回false
     * @return boolean 是否为周杰倫版本
     * @author zyanhao
     */
    public static boolean isJayVersion(){
        String starName = StarAppConfig.getConfig(StarAppConfig.STAR_VERSION);
        if (starName.equals(StarAppConst.StarVersion.JAY)){
            return true;
        }
        return false;
    }

}
